#!/usr/bin/python
#-*-coding: utf-8 -*-

u"""
:name: empty
:author: ANONYMOUS
:license: UNKNOWN
"""
__all__ = [u'HandlerPart']

########## DO NOT CHANGE THESE LINES ###########################################
import sys
from pylot.core import (ENCODING, Path)
try : __file__
except NameError : co = sys._getframe(0).f_code ; __file__ = co.co_filename
ufile = __file__.decode(ENCODING)
if ufile.strip() : PLUGIN_PATH = Path(ufile).abspath().parent
else : PLUGIN_PATH = Path(u'.').abspath()
########## DO NOT CHANGE THESE LINES ###########################################

from pylot.core import (check_type, hardbook, Plugin, Utils,
                           available_plugins)
from pylot.interfaces import (HandlerInterface)

class HandlerPart (HandlerInterface):
  def __init__ (self, plugin_path=None, plugin_id=None):
    if plugin_path is None : plugin_path = PLUGIN_PATH
    HandlerInterface.__init__(self, plugin_path, plugin_id)

    self.i18n = self.addPlugin(u'tools_i18n', plugin_id=u'i18n')
    self.testing = self.addPlugin(u'tools_testing', plugin_id=u'testing')

  def checkPlugin2(self, plugin_path):
    libcheck.check_plugin(plugin_path, self.io, tr_=self.tr_)

  def checkPlugin(self, plugin_name):
    u"""
    Launches pylint for all python files of plugin "plugin_name"
    
    :param plugin_name: plugin's name, for example u'tools_testing'
    :type plugin_name: :obj:`unicode`
    """
    plugin = Plugin(plugin_name)
    plugin_path = plugin.path
    return self.testing.pyLintFile(plugin_path, report=True)

  def testPlugin(self, plugin_name):
    u"""
    Launches doctests available for plugin "plugin_name"
    
    :param plugin_name: plugin's name, for example u'tools_testing'
    :type plugin_name: :obj:`unicode`
    """
    plugin = Plugin(plugin_name)
    handler = plugin.handler_class().init()
    globs = {
      'HandlerPart':plugin.handler_class,
      'CliPart':plugin.cli_class,
      'GuiPart':plugin.gui_class,
      'handler':handler,
      self.name:handler,
      sys:sys,
      }
    results = self.testing.doctestFiles(plugin.path, u'*.rst', globs=globs)
    self.testing.displayResults()

  def actionAutoWritePluginReference(self, plugin_name):
    u"""
    This action generates a class reference file for each class in pylot.
    Generation is automatic but can be customized using py file configuration
    in desc_MODULE directories, where MODULE is 'core', 'qtgui', etc.
    
    Rst files are saved in :
      - :file:`pylot/doc/user_manual/reference/MODULE/ClassName.rst`
    Configuration in
      - :file:`pylot/doc/user_manual/reference/MODULE/desc_MODULE/ClassName.py`
    
    """
    package = u'plugins'
    module_list = [plugin_name.encode(ENCODING)]

    package_obj, py_objects = self.testing.extractPyObjects(package, module_list)

    for mod in py_objects['classes']:
      umod = mod.decode(ENCODING)
      udesc = hardbook(u'pylotsrc', u'plugins', umod, u'docs_and_tests', u'references')
      self.testing.writeReference(package, udesc, umod, py_objects,
                           root_dir=udesc.parent, title=u'Plugin %s' % umod)

  def actionCheckPlugin(self):
    u"""
    Like :meth:`~tools_testing.HandlerPart.checkPlugin` but uses configuration
    [u'lastpaths'][u'plugins'] value for plugin's name.
    """
    name = self.testing.opt[u'lastpaths'][u'plugins'].value.name
    self.checkPlugin(name)

  def actionTestPlugin(self):
    u"""
    Like :meth:`~tools_testing.HandlerPart.testPlugin` but uses configuration
    [u'lastpaths'][u'plugins'] value for plugin's name.
    """
    name = self.testing.opt[u'lastpaths'][u'plugins'].value.name
    self.testPlugin(name)

  def actionWritePluginRstIndex(self):
    index = Utils.writefile(hardbook(u'plugins', u'autoindex.rst'),
                            security=u'force')
    content = u"""
=================
Available Plugins
=================

.. toctree::
  :maxdepth: 1

"""
    index.write(content)
    for plugin_name in available_plugins() :
      index.write(u'  %s/docs_and_tests/index.rst\n' % plugin_name)
    index.close()

  def actionCompileAllPluginTranslations(self):
    self.process.wait = True
    for plugin_name in available_plugins() :
      self.io.write(plugin_name, style=u'title')
      plugin_path = hardbook(u'extensions', u'plugins', plugin_name)
      self.i18n.compileTranslation(plugin_path)

  def writeSettings(self, settings, common=None):
    # we redefine method because we don't want to read and save all 
    # children's options
    if common is None :
      common = settings
    for book_id in self.i18n.opt :
      settings.beginGroup(u'plugin_editor_%s' % book_id)
      settings.setBook(self.i18n.opt[book_id])
      settings.endGroup()
    settings.beginGroup(u'plugin_editor_doctests')
    settings.setBook(self.testing.opt[u'doctests'])
    settings.endGroup()

  def readSettings(self, settings, common=None):
    # we redefine method because we don't want to read and save all 
    # children's options
    if common is None :
      common = settings
    for book_id in self.i18n.opt :
      settings.beginGroup(u'plugin_editor_%s' % book_id)
      book = settings.getBook(default_book=self.i18n.opt[book_id])
      self.i18n.opt[book_id].userUpgrade(book)
      settings.endGroup()
    settings.beginGroup(u'plugin_editor_doctests')
    book = settings.getBook(default_book=self.testing.opt[u'doctests'])
    self.testing.opt[u'doctests'].userUpgrade(book)
    settings.endGroup()

if __name__ == '__main__':
  u"""
  Example of script
  """
  handler = HandlerPart()
  handler.init()
  handler.example_method()
